package com.hooper.service.impl;

import cn.hutool.json.JSONUtil;
import com.hooper.exception.BusinessException;
import com.hooper.mapper.SysRoleMapper;
import com.hooper.mapper.SysUserRoleMapper;
import com.hooper.model.dto.UserRoleDto;
import com.hooper.model.system.SysUserRole;
import com.hooper.model.vo.UserRoleChangeVo;
import com.hooper.service.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

import static com.hooper.emun.ResultCodeEnum.*;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/04/01/16:03
 */
@Service
@Slf4j
public class UserRoleServiceImpl implements UserRoleService {

    @Resource
    private SysUserRoleMapper userRoleMapper;
    @Resource
    private SysRoleMapper roleMapper;

    @Override
    public void addUserRole(UserRoleChangeVo changeVo) {
        if (changeVo == null) {
            throw new BusinessException(PARAM_ERROR, "请求参数为空");
        }
        List<Long> roleIdList = changeVo.getRoleIdList();
        log.info("roleIdList:{}", roleIdList);
        Long userId = changeVo.getUserId();
        if (userId == null || CollectionUtils.isEmpty(roleIdList)) {
            throw new BusinessException(NULL_PARAM);
        }
        //查询该用户的角色
        SysUserRole sysUserRole = userRoleMapper.selectById(userId);
        //若不存在则新增
        if (sysUserRole == null) {
            sysUserRole = new SysUserRole();
            sysUserRole.setId(userId);
            sysUserRole.setRoleIds(JSONUtil.toJsonStr(roleIdList));
            userRoleMapper.insert(sysUserRole);
            return;
        }
        //若存在则更新
        userRoleMapper.updateRoleByUserId(userId, JSONUtil.toJsonStr(roleIdList));
    }


    @Override
    public UserRoleDto getUserRolesById(Long id) {
        SysUserRole userRole = userRoleMapper.selectById(id);
        log.info("userRole:{}", userRole);
        UserRoleDto roleDto = new UserRoleDto();
        roleDto.setAllRoles(roleMapper.selectAll());
        if (userRole == null || userRole.getRoleIds() == null) {
            userRole = new SysUserRole();
            userRole.setId(id);
            roleDto.setRoles(Collections.emptyList());
            return roleDto;
        }
        List<Long> list = JSONUtil.toList(userRole.getRoleIds(), Long.class);
        roleDto.setRoles(list);
        log.info("roleDto:{}", roleDto);
        return roleDto;
    }
}
